package com.mantru.iotpot.modbus;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.webkit.JavascriptInterface;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.*;
import java.util.*;

public class SaveLogThread extends Thread
{
	private String log_data = "", log_id = "";
	public SaveLogThread(String device_id, String data)
	{
		log_id = device_id;
		log_data = data.trim();
	}

	@Override
	public void run()
	{
		try
		{
			SaveLog(log_data);
		}
		catch(Exception e)
		{
			Log("SaveLogThread Run Error:" + e.getMessage());
		}
		// this.stop();
	}

	public void Log(String str)
	{
		Date nowDate = new Date();
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String log_str = "[" + format.format(nowDate) + "] " + str;

		System.out.println(log_str);
	}

	public void SaveLog(String value)
	{
		String api_url = "?txt_type=/pot/save_log/&device_id=" + log_id + "&code=200&timestamp=" + Common.GetTimeStamp13() + "&data=" + URLEncoder.encode(value);
		HttpApi_HttpGet(api_url);
	}

	private int HttpApi_HttpGet(String short_url)
	{
		String http_long_url = Common.API_Server_Url;
		if (short_url.trim().startsWith("?") == false)
			http_long_url += "?";
		if (short_url.trim().toLowerCase().startsWith("http") == false)
			http_long_url += short_url;

		String return_json = "";
		int error_code = 0;      //0表示没有发生异异，1表示有异常
		try
		{
			URL url = new URL(http_long_url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			InputStream is = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder builder = new StringBuilder();
			String line = "";
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			return_json = builder.toString();
			is.close();
			conn.disconnect();
		}
		catch(Exception ex)
		{
			error_code = 1;
			return_json = "error=" + ex.getMessage();
		}

		return 0;
	}



}
